package xdu.lz.stage4_atomic.chapter5_atomicxxxArray;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * Created at 2019/10/17 0017 下午 6:06
 * 通过原子的方式更新数组里的某个元素，Atomic包提供了以3类
 * AtomicIntegerArray：原子更新整型数组里的元素。
 * AtomicLongArray：原子更新长整型数组里的元素。
 * AtomicReferenceArray：原子更新引用类型数组里的元素。
 */
public class AtomicIntegerArray2 {

    private static int threadCount = 100;

    private static CountDownLatch countDown = new CountDownLatch(threadCount);

    private static int[] array = new int[10];

    //这里也可以直接传递一个长度，底层会创建一个数组
    //如果传数组，底层则是拷贝当前数组，之后当前数组已经没用了，要获取底层的数组，就是atoArray
    private static  AtomicIntegerArray atoArray = new AtomicIntegerArray(array);


    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[threadCount];
        /**
         * 每个线程对元组进行更新100次
         */
        for (int count = 0; count < threadCount; count++) {
            threads[count] = new Thread(()->{
                for (int i = 0; i < 100; i++) {
                    for (int j = 0; j < 10; j++) {//所有元素+1
                        atoArray.getAndIncrement(j);
                    }
                }
                countDown.countDown();
            });
        }
        for (int i = 0; i < threadCount; i++) {
            threads[i].start();
        }
        countDown.await();

        for (int i = 0; i < 10; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
        for(int i=0;i<10;i++){
            System.out.print(atoArray.get(i)+" ");
        }
    }


}
